using System.Collections.Generic;
using UnityEngine;

namespace Exploder
{
	public class ExploderQueue
	{
		private readonly Queue<ExploderSettings> queue;

		private readonly ExploderObject exploder;

		public ExploderQueue(ExploderObject exploder)
		{
			this.exploder = exploder;
			queue = new Queue<ExploderSettings>();
		}

		public void Enqueue(ExploderObject.OnExplosion callback, GameObject obj)
		{
			ExploderSettings exploderSettings = new ExploderSettings(exploder);
			exploderSettings.Callback = callback;
			exploderSettings.Target = obj;
			exploderSettings.processing = false;
			ExploderSettings item = exploderSettings;
			queue.Enqueue(item);
			ProcessQueue();
		}

		private void ProcessQueue()
		{
			if (queue.Count > 0)
			{
				ExploderSettings exploderSettings = queue.Peek();
				if (!exploderSettings.processing)
				{
					exploderSettings.id = Random.Range(int.MinValue, int.MaxValue);
					exploderSettings.processing = true;
					exploder.StartExplosionFromQueue(exploderSettings);
				}
			}
		}

		public void OnExplosionFinished(int id)
		{
			ExploderSettings exploderSettings = queue.Dequeue();
			ProcessQueue();
		}
	}
}
